package com.cql.web.controller.business;

import com.cql.common.core.DO.MarkDO;
import com.cql.common.core.DO.UserDO;
import com.cql.common.core.DTO.MarkDTO;
import com.cql.common.core.base.AjaxResult;
import com.cql.common.core.base.BaseController;
import com.cql.common.core.base.page.TableDataInfo;
import com.cql.common.core.security.LoginUser;
import com.cql.common.utils.StringUtils;
import com.cql.framework.config.security.service.TokenService;
import com.cql.service.business.MarkService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @author cql
 */
@RestController
@RequestMapping("/mark")
public class MarkController extends BaseController {


    @Autowired
    private TokenService tokenService;

    @Autowired
    private MarkService markService;

    /**
     * 获取用户对该文章的mark
     *
     * @param momentId
     * @param request
     * @return
     */
    @GetMapping("/{momentId}")
    public AjaxResult getMarkByAccount(@PathVariable("momentId") Long momentId, HttpServletRequest request) {
        LoginUser loginUser = tokenService.getLoginUser(request);
        if (StringUtils.isNull(loginUser)) {
            throw new AccessDeniedException("您没有权限");
        }
        MarkDTO mark = markService.getMark(momentId, loginUser.getUserDO());
        return AjaxResult.success(mark);
    }

    /**
     * 创建mark
     * 权限校验，数据校验
     *
     * @param mark
     * @param request
     * @return
     */
    @PostMapping
    public AjaxResult createMark(@RequestBody MarkDO mark, HttpServletRequest request) {
        System.out.println(mark);
        UserDO userDO = tokenService.getLoginUser(request).getUserDO();
        mark.setUserId(userDO.getUserId());

        markService.insertMark(mark);

        return AjaxResult.success();
    }


    /**
     * 删除mark
     *
     * @param markId
     * @param request
     * @return
     */
    @PostMapping("/{markId}")
    public AjaxResult deleteMark(@PathVariable("markId") Long markId, HttpServletRequest request) {

        Long userId = tokenService.getLoginUser(request).getUserDO().getUserId();

        markService.deleteMark(markId, userId);


        return AjaxResult.success();
    }


    /**
     * 因为mark是比较隐私的东西，所以本系统设计mark只允许自己看
     *
     * @param request
     * @return
     */
    @GetMapping("/list")
    public TableDataInfo listMark(HttpServletRequest request) {
        Long userId = tokenService.getLoginUser(request).getUserDO().getUserId();

        startPage();

        List<MarkDO> markDTOS = markService.listMark(userId);

        return getDataTable(markDTOS);
    }


}
